#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

pthread_cond_t condition;
pthread_mutex_t mutex;
long thread_count;
void* thread_func(void* arg) {
    long arg_data = (long)arg;
    sleep(thread_count - arg_data);
    printf("thread id before: %d\n", arg_data);
    pthread_mutex_lock(&mutex);
    while (pthread_cond_wait(&condition, &mutex) != 0);
    printf("thread id: %d\n", arg_data);
    pthread_mutex_unlock(&mutex);
    printf("thread id after: %d\n", arg_data);
    return 0;
}
int main(int argc, char** argv) {
    pthread_cond_init(&condition, NULL);
    pthread_mutex_init(&mutex, NULL);
    thread_count = atoi(argv[1]);
    pthread_t* thread_handles = malloc(thread_count * sizeof(pthread_t));
    for (long i = 0; i < thread_count; ++i) {
        pthread_create(&thread_handles[i], NULL, thread_func, (void*)i);
    }
    sleep(4);
    //pthread_cond_signal(&condition);
    pthread_cond_broadcast(&condition);
    for (long i = 0; i < thread_count; ++i) {
        pthread_join(thread_handles[i], NULL);
    }
    free(thread_handles);
    pthread_cond_destroy(&condition);
    pthread_mutex_destroy(&mutex);
    return 0;
}
